package com.qd.qx.api;


import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.SSLSessionCache;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;

import com.qd.chatui.enity.MessageInfo;
import com.qd.chatui.util.Constants;
import com.qd.chatui.widget.EmotionInputDetector;
import com.qd.common.baserx.RxBus;
import com.qd.common.commonutils.LogUtils;
import com.qd.common.commonutils.SPUtils;
import com.qd.common.commonutils.ToastUitl;
import com.qd.qx.app.AppApplication;
import com.qd.qx.app.AppConstants;
import com.qd.qx.bean.ChatConfig;
import com.qd.qx.bean.MembersBean;
import com.qd.qx.bean.UserData;
import com.qd.qx.db.DbHelper;
import com.qd.qx.db.bean.MsgList;
import com.qd.qx.db.bean.User;
import com.qd.qx.im.ChatInfoUtils;
import com.qd.qx.im.ChatMsgIQ;
import com.qd.qx.im.ChatMsgIQProvider;
import com.qd.qx.im.ChatRoomInviteXml;
import com.qd.qx.im.ImRxBus;
import com.qd.qx.im.TaxiConnectionListener;
import com.qd.qx.im.event.HandleEvent;

import org.jivesoftware.smack.ConnectionListener;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.ReconnectionManager;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.StanzaListener;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.chat.Chat;
import org.jivesoftware.smack.chat.ChatManager;
import org.jivesoftware.smack.chat.ChatManagerListener;
import org.jivesoftware.smack.chat.ChatMessageListener;
import org.jivesoftware.smack.filter.AndFilter;
import org.jivesoftware.smack.filter.StanzaFilter;
import org.jivesoftware.smack.filter.StanzaTypeFilter;
import org.jivesoftware.smack.filter.ToFilter;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.packet.Stanza;
import org.jivesoftware.smack.provider.ProviderManager;
import org.jivesoftware.smack.roster.Roster;
import org.jivesoftware.smack.roster.RosterEntry;
import org.jivesoftware.smack.tcp.XMPPTCPConnection;
import org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration;
import org.jivesoftware.smackx.muc.Affiliate;
import org.jivesoftware.smackx.muc.DiscussionHistory;
import org.jivesoftware.smackx.muc.HostedRoom;
import org.jivesoftware.smackx.muc.InvitationListener;
import org.jivesoftware.smackx.muc.MultiUserChat;
import org.jivesoftware.smackx.muc.MultiUserChatManager;
import org.jivesoftware.smackx.muc.RoomInfo;
import org.jivesoftware.smackx.muc.packet.MUCUser;
import org.jivesoftware.smackx.offline.OfflineMessageManager;
import org.jivesoftware.smackx.vcardtemp.packet.VCard;
import org.jivesoftware.smackx.xdata.Form;
import org.jivesoftware.smackx.xdata.FormField;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Set;

/**
 * Code is far away from bug with the animal protecting
 * Author：ys on 2018/10/10
 * Function：im连接
 */
public class MyXMPPTCPConnection {
    private static MyXMPPTCPConnection mInstance;
    public static final String SERVER_NAME = ApiServerConstants.IM_URL;//主机名
    public static final String SERVER_IP = ApiServerConstants.IM_URL;//ip
    public static final int PORT = ApiServerConstants.IM_PROT;//端口
    private static DbHelper dbHelper;
    private XMPPTCPConnection connection;
    private User user;//用户信息
    public static String OnlineChatName = "";//当前正在聊天的用户名称
    public boolean connectAuto = true;//断开自动连接 开关 退出登录用


    public static MyXMPPTCPConnection getInstance() {
        if (mInstance == null) {
            synchronized (MyXMPPTCPConnection.class) {
                mInstance = new MyXMPPTCPConnection();
                dbHelper = new DbHelper(AppApplication.getAppContext());
                return mInstance;
            }
        }
        return mInstance;
    }

    /**
     * 初始化
     */
    public void initIM() {
        setConnectAuto(true);
        getConnection();
    }

    public DbHelper getDbHelper() {
        return dbHelper;
    }

    /**
     * 退出登录断开im连接
     */
    public void disconnectIM() {
        setConnectAuto(false);
        connection.disconnect();
        connection = null;
    }

    public boolean isConnectAuto() {
        return connectAuto;
    }

    public void setConnectAuto(boolean connectAuto) {
        this.connectAuto = connectAuto;
    }

    /**
     * 获得与服务器的连接
     *
     * @return
     */
    public XMPPTCPConnection getConnection() {
        try {
            if (connection == null) {
                XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration.builder()
                        .setHost(SERVER_IP)//服务器IP地址
                        //服务器端口
                        .setPort(PORT)
                        //设置登录状态
                        .setSendPresence(true)
                        //服务器名称
                        .setServiceName(SERVER_NAME)
                        //是否开启安全模式
                        .setSecurityMode(XMPPTCPConnectionConfiguration.SecurityMode.disabled)
                        .setResource(ApiServerConstants.XMPP_RESOURCE)
                        //是否开启压缩
                        .setCompressionEnabled(false)
                        //开启调试模式
                        .setDebuggerEnabled(true).build();
                connection = new XMPPTCPConnection(config);
                connection.connect();
                ApiServerConstants.IM_URL = connection.getServiceName();//重置为服务器的ip
                //断线重连
                ReconnectionManager reconnectionManager = ReconnectionManager.getInstanceFor(connection);
                reconnectionManager.enableAutomaticReconnection();
                // 添加連接監聽
//                TaxiConnectionListener connectionListener = new TaxiConnectionListener();
//                getConnection().addConnectionListener(connectionListener);
            }
            return connection;
        } catch (Exception e) {
            e.printStackTrace();
            ImRxBus.getInstance().post(new HandleEvent("LoginActivity", false));
        }
        return connection;
    }


    /**
     * 把带域名的名字截取成只有名字的字符
     *
     * @return
     */
    public String splitGetChatName(String name) {
        try {
            String[] strs = name.split("@");
            return strs[0];
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "无名";
    }

    /**
     * 截取域名
     *
     * @param name
     * @return
     */
    public String splitGetDoman(String name) {
        try {
            String[] strs = name.split("@");
            return strs[1];
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "0000";
    }

    /**
     * 获取用户信息
     *
     * @return
     */
    public User GetUser() {
        if (user != null) {
            return user;
        } else {
            return null;
        }
    }

    /**
     * 初始化聊天消息监听
     */
    public void initListener() {
        ChatManager manager = ChatManager.getInstanceFor(connection);
        //设置信息的监听
        final ChatMessageListener messageListener = new ChatMessageListener() {
            @Override
            public void processMessage(Chat chat, Message message) {
                //当消息返回为空的时候，表示用户正在聊天窗口编辑信息并未发出消息
                if (!TextUtils.isEmpty(message.getBody())) {
                    chatMessageRecive(message);
                }
            }
        };
        ChatManagerListener chatManagerListener = new ChatManagerListener() {

            @Override
            public void chatCreated(Chat chat, boolean arg1) {
                chat.addMessageListener(messageListener);
            }
        };
        manager.addChatListener(chatManagerListener);
    }

    /**
     * 收到消息后解析消息 单群 通用操作
     *
     * @param message
     */
    private void chatMessageRecive(Message message) {
        try {
            MessageInfo messageInfo = parseChatMessage(message);
            //群过滤自己的消息
            if (messageInfo.getFromName().contains("conference") &&
                    UserData.getInstance().getChatName().equals(messageInfo.getMsgSendFrom())) {
                return;
            }

            //截取后为 名字+@+域名
            message.setFrom(message.getFrom().split("/")[0]);
            dbHelper.insertOneMsg(user.getUser_id(), message.getFrom(), messageInfo.getMsgChatId(), messageInfo.getContent(), messageInfo.getSendTime(), messageInfo.getMsgSendFrom(),
                    messageInfo.getType(),
                    messageInfo.getMsgType(), messageInfo.getSendState(), messageInfo.getHeader(),
                    true, messageInfo.getRealName(), messageInfo.getRealName(), messageInfo.getRoomName());
            ImRxBus.getInstance().post(message);
            refreshAllUnreadCount();
            //正在聊天的用户 收到该消息不响声音
//            if ((!OnlineChatName.equals(message.getFrom())) && (!SPUtils.getSharedStringData(AppConstants.CHAT_MESSAGE_NORING).equals(message.getFrom()))) {
//                playSound();
//            }
            if ((!OnlineChatName.equals(message.getFrom()))) {
                playSound();
//                ChatConfig chatConfig = ChatInfoUtils.getInstance().getChatConfig(message.getFrom());
//                if (null == chatConfig) {
//                    playSound();
//                    // ChatInfoUtils.getInstance().getGroupConfig(UserData.getInstance().getRefCode(),message.getFrom(),null);
//                } else {
//                    if (chatConfig.getIsRing() == 1) {
//                        playSound();
//                    }
//                }
            }
        } catch (final Exception e) {
            e.printStackTrace();
            new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    ToastUitl.showShort("收到消息出现异常：" + e.toString());
                }
            });

        }
    }


    /**
     * xmpp 个人信息
     *
     * @param user
     * @return
     */
    public VCard getUserVCard(String user) {
        VCard vcard = new VCard();
        try {
            vcard.load(connection, user);
        } catch (SmackException.NoResponseException e) {
            e.printStackTrace();
        } catch (XMPPException.XMPPErrorException e) {
            e.printStackTrace();
        } catch (SmackException.NotConnectedException e) {
            e.printStackTrace();
        }
        return vcard;
    }

    /**
     * 刷新获取所有未读消息
     */
    public int refreshAllUnreadCount() {
        List<MsgList> getMsgAllList = dbHelper.getMsgAllList(user.getUser_id());
        int count = 0;
        if (null != getMsgAllList && 0 != getMsgAllList.size()) {
            for (MsgList msgList : getMsgAllList) {
                count = msgList.getUnread_count() + count;
            }
            RxBus.getInstance().post(AppConstants.REFRESH_ALLUNREADCOUNT, count);
        }
        return count;
    }


    /**
     * 解析消息数据
     *
     * @return
     */
    //TODO 解析聊天数据
    public MessageInfo parseChatMessage(Message message) {
        MessageInfo messageInfo = new MessageInfo();
        messageInfo.setFromName(message.getFrom().split("/")[0]);     //截取后为 名字+@+域名
        messageInfo.setContent(message.getBody());
        messageInfo.setSendTime(null == message.getBody("sendTime") ? "" : message.getBody("sendTime"));
        messageInfo.setMsgType(null == message.getBody("msgType") ? "" : message.getBody("msgType"));
        messageInfo.setMsgChatId(null == message.getBody("msgChatId") ? "" : message.getBody("msgChatId"));
        messageInfo.setRealName(null == message.getBody("realName") ? "" : message.getBody("realName"));
        //messageInfo.setHeader(null == message.getBody("header") ? "" : message.getBody("header"));
        messageInfo.setRoomName(null == message.getBody("roomName") ? "" : message.getBody("roomName"));
        messageInfo.setMsgSendFrom(null == message.getBody("sendFrom") ? "" : message.getBody("sendFrom"));
        //以下是本地用
        messageInfo.setSendState(Constants.CHAT_ITEM_SEND_SUCCESS);
        if (messageInfo.getMsgType().equals(EmotionInputDetector.sendType_Tips)) {
            messageInfo.setType(Constants.CHAT_ITEM_TYPE_TIPS);
        } else {
            messageInfo.setType(Constants.CHAT_ITEM_TYPE_LEFT);//1 自己 2别人 3 公告
        }
        return messageInfo;
    }

    /**
     * 聊天单条消息id的格式
     *
     * @param name
     * @return
     */
    public String newMsgChatId(String name) {
        String time = System.currentTimeMillis() + "";
        String splTime = time.substring(0, 10);
        return name + splTime;
    }

    /**
     * 是否连接成功
     *
     * @return
     */
    public boolean isConnectedXmpp() {
        if (connection == null) {
            return false;
        }
        if (!connection.isConnected()) {
            try {
                connection.connect();
                return true;
            } catch (Exception e) {
                return false;
            }
        }
        return true;
    }

    /**
     * 登录
     *
     * @param userName
     * @param password
     */
    public void login(final String userName, final String password) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                getConnection();
                if (!isConnectedXmpp()) {
                    return;
                }
                try {
                    MyXMPPTCPConnection.this.connection.login(userName, password);//登录
                    //设置成在线，这里如果改成unavailable则会显示用户不在线
                    Presence presence = new Presence(Presence.Type.available);
                    presence.setStatus("在线");
                    MyXMPPTCPConnection.this.connection.sendStanza(presence);//发送Presence包
                    //String loginName, String userName, String userPsd
                    user = dbHelper.SetUser(userName, userName + "@" + ApiServerConstants.IM_URL, password, UserData.getInstance().getHeaderImg()
                            , UserData.getInstance().getRealName());//插入数据库
                    getOfflineMessage();//一上线获取离线消息
                    initListener();//登录成功开启消息监听
                    ImRxBus.getInstance().post(new HandleEvent("LoginActivity", true));
                    initChatGroupListener();//登录成功开启群聊消息监听

                    //ChatIQInit();//iq 初始化
                } catch (Exception e) {
                    e.printStackTrace();
                    // login(userName, password);
                    //   ImRxBus.getInstance().post(new HandleEvent("LoginActivity", false));
                }
            }
        }).start();
    }

//    private void initVcard() {
//        VCard vCard = new VCard();
//        vCard.setEmailHome("foo@fee.bar");
//        vCard.setNickName(UserData.getInstance().getRealName());
//        vCard.setField("TITLE", "Mr");
//        vCard.setField("headerImg", UserData.getInstance().getHeaderImg());
//        try {
//            vCard.save(connection);
//        } catch (SmackException.NoResponseException e) {
//            e.printStackTrace();
//        } catch (XMPPException.XMPPErrorException e) {
//            e.printStackTrace();
//        } catch (SmackException.NotConnectedException e) {
//            e.printStackTrace();
//        }
//    }

    /**
     * 一上线获取离线消息
     * 设置登录状态为在线
     */
    private void getOfflineMessage() {
        OfflineMessageManager offlineManager = new OfflineMessageManager(connection);
        try {
            List<Message> list = offlineManager.getMessages();
            for (Message message : list) {
                //JSONObject object = new JSONObject(message.getBody());
                //保存离线信息
                MessageInfo messageInfo = parseChatMessage(message);
                message.setFrom(message.getFrom().split("/")[0]);
                dbHelper.insertOneMsg(user.getUser_id(), message.getFrom(), messageInfo.getMsgChatId(), messageInfo.getContent(), messageInfo.getSendTime(), message.getFrom(),
                        Constants.CHAT_ITEM_TYPE_LEFT,
                        messageInfo.getMsgType(), messageInfo.getSendState(), messageInfo.getHeader(),
                        true, messageInfo.getRealName(), messageInfo.getRealName(), messageInfo.getRoomName());
                List<String> imgs = new ArrayList<>();
                imgs.add(messageInfo.getHeader());
            }
            //删除离线消息
            offlineManager.deleteMessages();
            //将状态设置成在线
            Presence presence = new Presence(Presence.Type.available);
            connection.sendStanza(presence);
        } catch (Exception e) {
            e.printStackTrace();
            LogUtils.loge("离线消息" + e.toString());
        }
    }


    /**
     * 获取指定好友用户信息
     *
     * @param user 用户名
     * @return
     */

    public RosterEntry getUserInfo(String user) {
        if (isConnectedXmpp()) {
            return Roster.getInstanceFor(connection).getEntry(user);
        } else {
            throw new NullPointerException("服务器连接失败，请先连接服务器");
        }
    }

    /**
     * 添加好友
     *
     * @param account   帐号
     * @param nickName  昵称
     * @param groupName 组名
     */
//    public boolean addFriend(String account, String nickName, String[] groupName) {
//        try {
//            Roster.getInstanceFor(connection).createEntry(account + "@" + SERVER_IP, "", groupName);
//            Log.e("TAG", account + "@" + SERVER_IP + "/smack");
//            return true;
//        } catch (Exception e) {
//            e.printStackTrace();
//            return false;
//        }
//    }


    /**
     * 播放系统声音提示
     */
    Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

    public void playSound() {
        Ringtone r = RingtoneManager.getRingtone(AppApplication.getAppContext(), notification);
        r.play();
    }

    /**
     * 好友信息监听
     */
//    public void requestListener() {
//        //条件过滤
//        StanzaFilter filter = new AndFilter();
//        StanzaListener listener = new StanzaListener() {
//            @Override
//            public void processPacket(Stanza packet) {
//                Presence p = (Presence) packet;
//                Log.e("TAG", "--" + p.getFrom() + "--" + p.getType());
//                if (p.getType().toString().equals("subscrib")) {
//                    ImRxBus.getInstance().post(new FriendListenerEvent(p.getFrom(), "subscrib", "ChatUiMainActivity"));
//                } else if (p.getType().toString().equals("subscribed")) {
//                    ImRxBus.getInstance().post(new FriendListenerEvent(p.getFrom(), "subscribed", "ChatUiMainActivity"));
//                } else if (p.getType().toString().equals("unsubscribe")) {
//                    ImRxBus.getInstance().post(new FriendListenerEvent(p.getFrom(), "unsubscribe", "ChatUiMainActivity"));
//                }
//            }
//        };
//        connection.addAsyncStanzaListener(listener, filter);
//    }

//    /**
//     * 拒绝好友申请
//     *
//     * @param userId 用户id
//     */
//    public void refuse(String userId) {
//        Presence presence = new Presence(Presence.Type.unsubscribe);
//        presence.setTo(userId);
//        try {
//            connection.sendStanza(presence);
//        } catch (SmackException.NotConnectedException e) {
//            e.printStackTrace();
//        }
//    }
//
//    /**
//     * 接收好友申请
//     *
//     * @param userId 用户id
//     */
//    public void accept(String userId) {
//        Presence presence = new Presence(Presence.Type.subscribe);
//        presence.setTo(userId);
//        try {
//            connection.sendStanza(presence);
//        } catch (SmackException.NotConnectedException e) {
//            e.printStackTrace();
//        }
//    }
//
//    /**
//     * 创建一个新用户
//     *
//     * @param username 用户名
//     * @param password 密码
//     * @param attr     一些用户资料
//     * @see AccountManager
//     */
//    public void registerAccount(String username, String password, Map<String, String> attr) {
//        getConnection();
//        isConnectedXmpp();
//        AccountManager manager = AccountManager.getInstance(connection);
//        try {
//            if (attr == null) {
//                manager.createAccount(username, password);
//            } else {
//                manager.createAccount(username, password, attr);
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }


    /**
     * 群聊相关----------------------------------------------------------------------------------------------------------------
     */

    /**
     * 创建群聊
     *
     * @param roomName    聊天室名字
     * @param nickName    创建者在聊天室中的昵称
     * @param 、password   聊天室密码  不要密码
     * @param inviteUsers 邀请的成员
     * @return
     */
//    房间名称 text-single muc#roomconfig_roomname
//    描述 text-single muc#roomconfig_roomdesc
//    允许占有者更改主题 boolean muc#roomconfig_changesubject
//    最大房间占有者人数 list-single muc#roomconfig_maxusers
//    其 Presence 是 Broadcast 的角色 list-multi muc#roomconfig_presencebroadcast
//    列出目录中的房间 boolean muc#roomconfig_publicroom
//    房间是持久的 boolean muc#roomconfig_persistentroom
//    房间是适度的 boolean muc#roomconfig_moderatedroom
//    房间仅对成员开放 boolean muc#roomconfig_membersonly
//    允许占有者邀请其他人 boolean muc#roomconfig_allowinvites
//    需要密码才能进入房间 boolean muc#roomconfig_passwordprotectedroom
//    密码 text-private muc#roomconfig_roomsecret
//    能够发现占有者真实 JID 的角色 list-single muc#roomconfig_whois
//    登录房间对话 boolean muc#roomconfig_enablelogging
//    仅允许注册的昵称登录 boolean x-muc#roomconfig_reservednick
//    允许使用者修改昵称 boolean x-muc#roomconfig_canchangenick
//    允许用户注册房间 boolean x-muc#roomconfig_registration
//    房间管理员 jid-multi muc#roomconfig_roomadmins
//    房间拥有者 jid-multi muc#roomconfig_roomowners
    //TODO 创建群聊
    public MultiUserChat createChatGroup(String roomName, String nickName, List<String> inviteUsers, String groupNickName) {
        String password = "";
        String jid = roomName + "@conference." + connection.getServiceName();
        MultiUserChat muc;
        try {
            // 创建一个MultiUserChat
            muc = MultiUserChatManager.getInstanceFor(connection).getMultiUserChat(jid);
            // 创建聊天室
            boolean isCreated = muc.createOrJoin(nickName);
            if (isCreated) {
                // 获得聊天室的配置表单
                Form form = muc.getConfigurationForm();
                // 根据原始表单创建一个要提交的新表单。
                Form submitForm = form.createAnswerForm();
                // 向要提交的表单添加默认答复
                List<FormField> fields = form.getFields();
                for (int i = 0; fields != null && i < fields.size(); i++) {
                    if (FormField.Type.hidden != fields.get(i).getType() &&
                            fields.get(i).getVariable() != null) {
                        // 设置默认值作为答复
                        submitForm.setDefaultAnswer(fields.get(i).getVariable());
                    }
                }
                // 设置聊天室的新拥有者
                List owners = new ArrayList();
                owners.add(connection.getUser());// 用户JID
                submitForm.setAnswer("muc#roomconfig_roomowners", owners);
                // 设置聊天室是持久聊天室，即将要被保存下来
                submitForm.setAnswer("muc#roomconfig_persistentroom", true);
                // 房间仅对成员开放
                submitForm.setAnswer("muc#roomconfig_membersonly", true);//记录下 这里坑
                // 允许占有者邀请其他人
                submitForm.setAnswer("muc#roomconfig_allowinvites", true);
                if (password != null && password.length() != 0) {
                    // 进入是否需要密码
                    submitForm.setAnswer("muc#roomconfig_passwordprotectedroom", true);
                    // 设置进入密码
                    submitForm.setAnswer("muc#roomconfig_roomsecret", password);
                }
                // 能够发现占有者真实 JID 的角色
                // submitForm.setAnswer("muc#roomconfig_whois", "anyone");

                //设置房间最大用户数
                List<String> maxusers = new ArrayList<String>();
                maxusers.add("200");
                submitForm.setAnswer("muc#roomconfig_maxusers", maxusers);

                // 登录房间对话
                submitForm.setAnswer("muc#roomconfig_enablelogging", true);
                // 仅允许注册的昵称登录
                submitForm.setAnswer("x-muc#roomconfig_reservednick", true);
                // 允许使用者修改昵称
                submitForm.setAnswer("x-muc#roomconfig_canchangenick", false);
                // 允许用户注册房间
                submitForm.setAnswer("x-muc#roomconfig_registration", false);
                //新添加  真实群名称
                submitForm.setAnswer("muc#roomconfig_roomname", groupNickName);
                //默认群公告
                submitForm.setAnswer("muc#roomconfig_roomdesc", "未设置");
                // 发送已完成的表单（有默认值）到服务器来配置聊天室
                muc.sendConfigurationForm(submitForm);
                //创建完后 自己先加入一下
                muc.join(nickName);
                if (null != inviteUsers && inviteUsers.size() != 0) {
                    if (inviteGroupPeople(jid, inviteUsers, nickName)) {
                        return muc;
                    } else {
                        return null;
                    }
                }
//                ToastUitl.showShort("创建成功");
            } else {
                //ToastUitl.showShort("创建失败");
            }
        } catch (XMPPException | SmackException e) {
            e.printStackTrace();
            //   ToastUitl.showShort("创建失败" + e.toString());

            return null;
        }
        return muc;
    }

    /**
     * 邀请人员加入房间
     *
     * @param roomJid
     * @param userList
     * @param nickName
     * @return
     */
    public boolean inviteGroupPeople(String roomJid, List<String> userList, String nickName) {
        String reason = nickName + "邀请你加入群聊";
        String room = roomJid.toLowerCase(Locale.US);
        Message message = new Message();
        message.setTo(room);
        ChatRoomInviteXml chatRoomInviteXml = new ChatRoomInviteXml();
        chatRoomInviteXml.setUserS(userList);
        chatRoomInviteXml.setReason(reason);
        message.addExtension(chatRoomInviteXml);
        try {
            connection.sendStanza(message);
        } catch (SmackException.NotConnectedException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 转换群主
     *
     * @param roomJid
     * @param meJid
     * @param newManagerJid
     * @return
     */
    public boolean changeChatRoomManager(String roomJid, String meJid, String newManagerJid) {
        MultiUserChat muc;
        try {
            muc = MultiUserChatManager.getInstanceFor(connection).getMultiUserChat(roomJid);
            muc.grantAdmin(newManagerJid);
            muc.revokeAdmin(meJid);
            return true;
        } catch (XMPPException.XMPPErrorException e) {
            e.printStackTrace();
        } catch (SmackException.NoResponseException e) {
            e.printStackTrace();
        } catch (SmackException.NotConnectedException e) {
            e.printStackTrace();
        }
        return false;
    }


    /**
     * 获取聊天室显示名字
     *
     * @param jid
     * @return
     */
    public String getGroupNickName(String jid) {
        MultiUserChat muc;
        String groupNickName = "";
        // 获得聊天室的配置表单
        try {
            muc = MultiUserChatManager.getInstanceFor(connection).getMultiUserChat(jid);
            Form form = muc.getConfigurationForm();
            FormField formField = form.getField("muc#roomconfig_roomname");
            List<String> stringList = formField.getValues();
            if (null != stringList && stringList.size() != 0) {
                groupNickName = stringList.get(0);
                return groupNickName;
            }
        } catch (SmackException.NoResponseException e) {
            e.printStackTrace();
        } catch (XMPPException.XMPPErrorException e) {
            e.printStackTrace();
        } catch (SmackException.NotConnectedException e) {
            e.printStackTrace();
        }
        return groupNickName;
    }

    /**
     * 编辑群名称
     *
     * @param jid
     * @param groupName
     */
    public boolean editGroupName(String jid, String groupName) {
        MultiUserChat muc;
        muc = MultiUserChatManager.getInstanceFor(connection).getMultiUserChat(jid);
        // 获得聊天室的配置表单
        Form form = null;
        try {
            form = muc.getConfigurationForm();
            // 根据原始表单创建一个要提交的新表单。
            Form submitForm = form.createAnswerForm();
            //新添加  真实群名称
            submitForm.setAnswer("muc#roomconfig_roomname", groupName);
            // 发送已完成的表单（有默认值）到服务器来配置聊天室
            muc.sendConfigurationForm(submitForm);
        } catch (SmackException.NoResponseException e) {
            e.printStackTrace();
            return false;
        } catch (XMPPException.XMPPErrorException e) {
            e.printStackTrace();
            return false;
        } catch (SmackException.NotConnectedException e) {
            e.printStackTrace();
            return false;
        }
        //操作成功 更新数据库
        if (updateSqlNewName(jid, groupName)) {
            return true;
        }
        return false;
    }

    /**
     * 根据jid 获取群描述
     *
     * @param jid
     * @return
     */
    public String getGroupDesc(String jid) {
        MultiUserChat muc;
        String desc = "";
        // 获得聊天室的配置表单
        try {
            muc = MultiUserChatManager.getInstanceFor(connection).getMultiUserChat(jid);
            Form form = muc.getConfigurationForm();
            FormField formField = form.getField("muc#roomconfig_roomdesc");
            List<String> stringList = formField.getValues();
            if (null != stringList && stringList.size() != 0) {
                desc = stringList.get(0);
                return desc;
            }
        } catch (SmackException.NoResponseException e) {
            e.printStackTrace();
        } catch (XMPPException.XMPPErrorException e) {
            e.printStackTrace();
        } catch (SmackException.NotConnectedException e) {
            e.printStackTrace();
        }
        return desc;
    }

    /**
     * 设置群描述
     *
     * @param jid
     * @param groupDesc
     * @return
     */
    public boolean editGroupDesc(String jid, String groupDesc) {
        MultiUserChat muc;
        muc = MultiUserChatManager.getInstanceFor(connection).getMultiUserChat(jid);
        // 获得聊天室的配置表单
        Form form = null;
        try {
            form = muc.getConfigurationForm();
            // 根据原始表单创建一个要提交的新表单。
            Form submitForm = form.createAnswerForm();
            //群描述
            submitForm.setAnswer("muc#roomconfig_roomdesc", groupDesc);
            // 发送已完成的表单（有默认值）到服务器来配置聊天室
            muc.sendConfigurationForm(submitForm);
        } catch (SmackException.NoResponseException e) {
            e.printStackTrace();
            return false;
        } catch (XMPPException.XMPPErrorException e) {
            e.printStackTrace();
            return false;
        } catch (SmackException.NotConnectedException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 根据jid 更新对应的数据库 显示的名字
     *
     * @param jid
     * @param newName
     * @return
     */
    private boolean updateSqlNewName(String jid, String newName) {
        MsgList msgList = dbHelper.getMsgList(user.getUser_id(), jid);
        if (null != msgList) {
            dbHelper.updateNameMsgList(user.getUser_id(), msgList.getMsg_list_id(), newName);
            return true;
        }
        return false;

    }


    /**
     * 移除群成员
     *
     * @param jid
     * @param userJid
     * @return
     */
    public boolean removeGroupPeople(String jid, Collection<String> userJid) {
        MultiUserChat muc;
        try {
            // 创建一个MultiUserChat
            muc = MultiUserChatManager.getInstanceFor(connection).getMultiUserChat(jid);
            if (null != muc && null != userJid) {
                try {
                    muc.banUsers(userJid);
                } catch (XMPPException.XMPPErrorException e) {
                    e.printStackTrace();
                    return false;
                } catch (SmackException.NoResponseException e) {
                    e.printStackTrace();
                    return false;
                }
                return true;
            }
        } catch (SmackException.NotConnectedException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 加入一个群聊
     *
     * @param jid       聊天室ip 格式为>>群组名称@conference.ip
     * @param nickName  用户在聊天室中的昵称
     * @param `password 聊天室密码 没有密码则传""
     * @return
     */
    public MultiUserChat joinChatGroup(String jid, String nickName) {
        try {
            // 使用XMPPConnection创建一个MultiUserChat窗口
            MultiUserChat muc = MultiUserChatManager.getInstanceFor(connection).getMultiUserChat(jid);
            // 聊天室服务将会决定要接受的历史记录数量
            DiscussionHistory history = new DiscussionHistory();
            history.setMaxChars(0);
            // 用户加入聊天室
            String password = "";
            muc.join(nickName, password);
            return muc;
        } catch (XMPPException | SmackException e) {
            e.printStackTrace();
            if ("XMPPError: not-authorized - auth".equals(e.getMessage())) {
                //需要密码加入
            }
            return null;
        }
    }

    /**
     * 获取服务器上的所有群组
     */
    private List<HostedRoom> getHostedChatGroup() {
        MultiUserChatManager manager = MultiUserChatManager.getInstanceFor(connection);
        try {
            //serviceNames->conference.106.14.20.176
            List<String> serviceNames = manager.getServiceNames();
            for (int i = 0; i < serviceNames.size(); i++) {
                return manager.getHostedRooms(serviceNames.get(i));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取用户所在的群
     *
     * @return
     */
    private Set<String> getJoinGroupRoom() {
        MultiUserChatManager manager = MultiUserChatManager.getInstanceFor(connection);
        try {
            //serviceNames->conference.106.14.20.176
            Set<String> joinRooms = manager.getJoinedRooms();
            return joinRooms;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 退出群聊
     *
     * @param jid
     * @throws
     */
    public void quitRoom(String jid) {

        MultiUserChatManager multiUserChatManager = MultiUserChatManager.getInstanceFor(connection);
        MultiUserChat multiUserChat = multiUserChatManager.getMultiUserChat(jid);
        //删除群 并退出
        try {
            multiUserChat.destroy("", jid);
        } catch (SmackException.NoResponseException e) {
            e.printStackTrace();
        } catch (XMPPException.XMPPErrorException e) {
            e.printStackTrace();
        } catch (SmackException.NotConnectedException e) {
            e.printStackTrace();
        }

        //退出群
        try {
            multiUserChat.leave();
        } catch (SmackException.NotConnectedException e) {
            e.printStackTrace();
        }
    }

    /**
     * @param jid 格式为>>群组名称@conference.ip
     */
    private void initChatGroupListener(String jid) {
        MultiUserChat multiUserChat = MultiUserChatManager.getInstanceFor(connection).getMultiUserChat(jid);
        multiUserChat.addMessageListener(new MessageListener() {
            @Override
            public void processMessage(final Message message) {
                //当消息返回为空的时候，表示用户正在聊天窗口编辑信息并未发出消息
                if (!TextUtils.isEmpty(message.getBody())) {
                    //收到的消息
                    chatMessageRecive(message);
                }
            }
        });
    }

//    /**
//     * 查询会议室成员名字
//     *
//     * @param jid
//     */
//    public List<MembersBean> findMulitUser(String jid) {
//        MultiUserChat muc = MultiUserChatManager.getInstanceFor(connection).getMultiUserChat(jid);
//        List<MembersBean> membersList = new ArrayList();
//        List<Affiliate> members = null;
//        try {
//            members = muc.getMembers();
//        } catch (SmackException.NoResponseException e) {
//            e.printStackTrace();
//        } catch (XMPPException.XMPPErrorException e) {
//            e.printStackTrace();
//        } catch (SmackException.NotConnectedException e) {
//            e.printStackTrace();
//        }
//        if (null != members) {
//            for (Affiliate affiliate : members) {
//                membersList.add(new MembersBean(affiliate.getJid(), affiliate.getNick()));
//            }
//        }
//        return membersList;
//    }

    /**
     * 初始化群的聊天监听
     */
    //TODO 群聊加监听
    public void initChatGroupListener() {
        List<HostedRoom> hostedRooms = getHostedChatGroup();
        if (null != hostedRooms) {
            for (HostedRoom hostedRoom : hostedRooms) {
                joinChatGroup(hostedRoom.getJid(), UserData.getInstance().getRealName());
                initChatGroupListener(hostedRoom.getJid());
            }
        }

//        Set<String> joinRooms = getJoinGroupRoom();
//        if (null != joinRooms) {
//            for (String jid : joinRooms) {
//                initChatGroupListener(jid);
//            }
//        }


        //群聊被邀请监听
        MultiUserChatManager.getInstanceFor(connection).addInvitationListener(new InvitationListener() {
            @Override
            public void invitationReceived(XMPPConnection conn, MultiUserChat room, String inviter, String reason, String password, Message message) {
                //收到加群消息后 加入该群
                try {
                    joinChatGroup(room.getRoom(), UserData.getInstance().getRealName());
                } catch (final Exception e) {
                    e.printStackTrace();
                }
                //添加该群的监听
                initChatGroupListener(room.getRoom());
            }
        });
    }

    /**
     * 初始化IQ
     */
//    public void ChatIQInit() {
//        try {
//            StanzaFilter filter = new AndFilter(new StanzaTypeFilter(ChatMsgIQ.class)
//                    , new ToFilter(connection.getUser()));//配置过滤器
//            connection.addSyncStanzaListener(stanzaListener, filter);//设置监听器
//            ProviderManager.addIQProvider("info", "match:info", new ChatMsgIQProvider());
//        } catch (Exception e) {
//            e.printStackTrace();
//            LogUtils.loge(e.toString());
//        }
//    }

//    /**
//     * 处理IQ的监听
//     */
//    private StanzaListener stanzaListener = new StanzaListener() {
//        @Override
//        public void processPacket(Stanza packet) {
//            // TODO Auto-generated method stub
//            //在这里就可以处理出去和进来的数据包
//
//        }
//    };
}
